package com.me.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;

public class SArrayAdaptor extends ArrayAdapter<String> {
	private final String MY_DEBUG_TAG = "CustomerAdapter";
	private ArrayList<String> history_items;
	private ArrayList<String> history_itemsAll;
	private ArrayList<String> suggested_items;
	private ArrayList<String> suggestions;
	private int viewResourceId;

	public SArrayAdaptor(Context context, int viewResourceId,
			ArrayList<String> history_items, ArrayList<String> suggested_items) {
		super(context, viewResourceId, history_items);
		this.history_items = history_items;
		this.history_itemsAll = (ArrayList<String>) history_items.clone();
		this.suggested_items = suggested_items;
		this.suggestions = new ArrayList<String>();
		this.viewResourceId = viewResourceId;
	}

	// public View getView(int position, View convertView, ViewGroup parent) {
	// View v = convertView;
	// if (v == null) {
	// LayoutInflater vi = (LayoutInflater)
	// getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	// v = vi.inflate(viewResourceId, null);
	// }
	// Customer customer = items.get(position);
	// if (customer != null) {
	// TextView customerNameLabel = (TextView)
	// v.findViewById(R.id.customerNameLabel);
	// if (customerNameLabel != null) {
	// // Log.i(MY_DEBUG_TAG, "getView Customer Name:"+customer.getName());
	// customerNameLabel.setText(customer.getName());
	// }
	// }
	// return v;
	// }

	@Override
	public Filter getFilter() {
		return nameFilter;
	}

	Filter nameFilter = new Filter() {

		@Override
		protected FilterResults performFiltering(CharSequence constraint) {
			if (constraint != null) {
				suggestions.clear();
				for (String history : history_itemsAll) {
					if (history.toLowerCase().startsWith(
							constraint.toString().toLowerCase())) {
						suggestions.add(history);
					}
				}
				FilterResults filterResults = new FilterResults();
				suggestions.addAll(suggested_items);
				filterResults.values = suggestions;
				filterResults.count = suggestions.size();
				return filterResults;
			} else {
				return new FilterResults();
			}
		}

		@Override
		protected void publishResults(CharSequence constraint,
				FilterResults results) {
			ArrayList<String> filteredList = (ArrayList<String>) results.values;
			if (results != null && results.count > 0) {
				clear();
				for (String c : filteredList) {
					add(c);
				}
				notifyDataSetChanged();
			}
		}
	};

}